package com.software.course.controller;


import com.software.course.enity.User;
import com.software.course.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    @Autowired
    private LoginService loginService;

    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model, HttpServletRequest request){
//        if(StringUtils.hasLength(testUser.getUserName() ) && "1234".equals(testUser.getPassword())){
//            session.setAttribute("loginUser",testUser);
//            System.out.println(testUser.getUserName());
//            System.out.println(testUser.getPassword());
//            return "redirect:/index.html";
//        }else {
//            model.addAttribute("msg","账号，或密码错误");
//            return "login";
//        }
        String account = request.getParameter("account");
        String password = request.getParameter("password");
         user= loginService.LoginUser(account, password);
        if(user != null){
            session.setAttribute("loginUser",user);
            int role = user.getRole();
//            session.setAttribute("role",role);
            System.out.println("当前用户权限为："+role);
            return "redirect:/index.html";
        }
        model.addAttribute("info","账户或密码不存在");
        return "login";
    }

    @GetMapping("/index.html")
    public String mainPage(HttpSession session, Model model){
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser != null){
            return "index";
        }else {
            model.addAttribute("msg","请重新登陆");
            return "login";
        }
    }

    @GetMapping("/profile.html")
    public String toProfile(){
        return "profile";
    }
}
